<?php

class Core_Action_Admin_System_Storage_Edit extends Action_Admin
{
	function execute($request, $initial = FALSE, $script = NULL)
	{
		if ($initial)
		{
			Agilet::setVar('breadcrum', array(
				array(
					'url' => 'admin/system',
					'label' => 'System'
				),
				array(
					'url' => 'admin/system/storage',
					'label' => 'Storage'
				)
			));

		}

		$service_id = $request -> getParam('service_id');
		$storage_id = $request -> getParam('id');

		$storageTable = Model::getTable('core/storage');
		$serviceTable = Model::getTable('core/storage/service');
		$storage = null;
		$service = null;

		if ($storage_id)
		{
			$storage = $storageTable -> find($storage_id) -> current();

			if ($storage)
			{
				$service_id = $storage -> getServiceId();
			}
		}

		if ($service_id)
		{
			$service = $serviceTable -> find($service_id) -> current();
		}

		if (!is_object($service))
		{
			$service = $serviceTable -> find('local') -> current();
		}

		$admin_form = $service -> admin_form;

		$title = $service -> getTitle();

		$form = Form::factory($admin_form);

		if ($request -> isGet() && is_object($storage))
		{
			$data2 = array();
			if (isset($storage -> serialized_data) && $storage -> serialized_data)
			{
				$data2 = unserialize($storage -> serialized_data);
			}
			$data = $storage -> toArray();
			$data = array_merge($data, $data2);
			$form -> setData($data);
		}

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			unset($data['_buttons']);

			if (!is_object($storage))
			{
				$storage = $storageTable -> fetchNew();
				$storage -> service_id = $service -> getId();
			}

			$storage -> fromArray($data);

			$storage -> save();

			$data['service_id'] = $data['service'] = $service -> getId();

			$storageTable -> set($storage -> getId(), $data);

			Response::redirect('admin/system/storage');
		}

		$request -> response = View::render($script = 'core/html/admin/edit', $data = array(
			'form' => $form,
			'title' => $title
		));
	}

}
